import router from '@/router';
import nprogress from 'nprogress';
import 'nprogress/nprogress.css';
import store from '@/store';
import { asyncRoutes } from '@/router';

const whileList = ['/login', '/404'];
// 全局前置守卫
router.beforeEach(async(to, from, next) => {
  nprogress.start()
  console.log('路由守卫触发')
  // console.log(store.getters.token)
  if (store.getters.token) {
    // console.log('有token,permisson拦截执行')
    if (to.path === '/login') {
      next('/') // next加路径后不会通过后置守卫处理
      nprogress.done()
    } else {
      // 判断是否获取过用户资料
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')
        // console.log(roles)
        // console.log(asyncRoutes)
        const filterRoutes = asyncRoutes.filter(item => roles.menus.includes(item.name))
        // console.log(filterRoutes)
        // 一定要先commit不然 404会渲染到菜单上
        store.commit('user/setRoutes', filterRoutes)
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path) // 目的是让路由拥有信息 router已知的缺陷
      } else {
        next() // 放过
      }
    }
  } else {
    if (whileList.includes(to.path)) {
      next()
    } else {
      next('/login')
      nprogress.done()
    }
  }
})

// 全局后置钩子
router.afterEach(() => {
  nprogress.done();
});
